import defaultSettings from '@/settings';
import { ThemeEnum } from '@/enums';
import { generateThemeColors, applyTheme, toggleDarkMode } from '@/utils/theme';

// 创建统一设置存储对象
const settingStorage = useStorage('setting', {
  tagsView: defaultSettings.tagsView,
  sidebarLogo: defaultSettings.sidebarLogo,
  fixedHeader: defaultSettings.fixedHeader,
  layout: defaultSettings.layout,
  watermarkEnabled: defaultSettings.watermarkEnabled,
  themeColor: defaultSettings.themeColor,
  theme: defaultSettings.theme,
});

export const useSettingsStore = defineStore('setting', () => {
  // 基本设置
  const settingsVisible = ref(false);

  // 通过计算属性访问设置对象
  const tagsView = computed({
    get: () => settingStorage.value.tagsView,
    set: (v) => (settingStorage.value.tagsView = v),
  });

  const sidebarLogo = computed({
    get: () => settingStorage.value.sidebarLogo,
    set: (v) => (settingStorage.value.sidebarLogo = v),
  });

  const fixedHeader = computed({
    get: () => settingStorage.value.fixedHeader,
    set: (v) => (settingStorage.value.fixedHeader = v),
  });

  const layout = computed({
    get: () => settingStorage.value.layout,
    set: (v) => (settingStorage.value.layout = v),
  });

  const watermarkEnabled = computed({
    get: () => settingStorage.value.watermarkEnabled,
    set: (v) => (settingStorage.value.watermarkEnabled = v),
  });

  const themeColor = computed({
    get: () => settingStorage.value.themeColor,
    set: (v) => (settingStorage.value.themeColor = v),
  });

  const theme = computed({
    get: () => settingStorage.value.theme,
    set: (v) => (settingStorage.value.theme = v),
  });

  // 监听主题变化
  watch(
    [theme, themeColor],
    ([newTheme, newThemeColor]) => {
      toggleDarkMode(newTheme === ThemeEnum.DARK);
      const colors = generateThemeColors(newThemeColor);
      applyTheme(colors);
    },
    { immediate: true },
  );

  // 设置更改函数
  const settingsMap = {
    fixedHeader,
    tagsView,
    sidebarLogo,
    layout,
    watermarkEnabled,
  };

  function changeSetting({ key, value }) {
    const setting = settingsMap[key];
    if (setting) setting.value = value;
  }

  function changeTheme(val) {
    theme.value = val;
    // vxeTheme.value = val;
  }

  function changeThemeColor(color) {
    themeColor.value = color;
  }

  function changeLayout(val) {
    layout.value = val;
  }

  return {
    settingsVisible,
    tagsView,
    fixedHeader,
    sidebarLogo,
    layout,
    themeColor,
    theme,
    watermarkEnabled,
    changeSetting,
    changeTheme,
    changeThemeColor,
    changeLayout,
  };
});
